package com.vim.modules.web.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.StringWriter;
import java.net.URL;
import java.util.Locale;
import java.util.Map;

/**
 * 代码自动生成工具生成-对应数据库表的操作的适配器类
 */

public class FreemarkerManager {
	private Configuration cfg;
	private FreemarkerManager() {
		cfg=this.initConfig("generator/");
	}

	private static FreemarkerManager _instance = new FreemarkerManager();
	public static FreemarkerManager getInstance() { return _instance; }

	/**
	 * 用统一的方法初始化配置信息
	 */
	@SuppressWarnings("deprecation")
	private Configuration initConfig(String configPath) {
		Configuration ccfg = new Configuration();
		try {
			String path = getClass().getClassLoader().getResource(configPath).toURI().getPath();
		    File file = new File(path);
			ccfg.setDirectoryForTemplateLoading(file);
			ccfg.setNumberFormat("#");
			ccfg.setEncoding(Locale.getDefault(), "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ccfg;
	}

	/**
	 * 根据map里面的数据和模板生成最终内容(根目录为：WEB-INF\templet)
	 */
	public String process(Map<?, ?> map, String templet) {
		return this.process(cfg, map, templet);
	}

	/**
	 * 根据map里面的数据和模板生成最终内容
	 */
	public String process(Configuration ccfg, Map<?, ?> map, String templet) {
		String r = "";
		StringWriter out = new StringWriter();
		try {
			Template t = ccfg.getTemplate(templet);
			t.process(map, out);
			r = out.getBuffer().toString();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
		return r;
	}
}
